//
//  HJEmoticonToolBar.swift
//  HJWeiBo
//
//  Created by 夏航军 on 16/10/8.
//  Copyright © 2016年 夏航军. All rights reserved.
//

import UIKit

enum EmoticonType : Int {
    case RECENT = 0
    case DEFAULT
    case EMOJI
    case LXH
}

class HJEmoticonToolBar: UIStackView {

    var lastBtn : UIButton?
    
    //闭包用于传递被点击的btn的值,从而改变CollectionView的组
    var emoticonTypeSelectClosure : ((EmoticonType) -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
        //设置轴
        axis = .horizontal
        //设置填充方法
        distribution = .fillEqually
        
        tag = 10000
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    func setupUI() {
        //最近
        addChildButtons(title: "最近", backImg: "compose_emotion_table_left", index: .RECENT)
        //默认
        addChildButtons(title: "默认", backImg: "compose_emotion_table_mid",index: .DEFAULT)
        //Emoji
        addChildButtons(title: "Emoji", backImg: "compose_emotion_table_mid",index: .EMOJI)
        //浪小花
        addChildButtons(title: "浪小花", backImg: "compose_emotion_table_right",index: .LXH)
        
    }

    
    private func addChildButtons(title : String , backImg : String , index : EmoticonType) {
        
        let btn = UIButton()
        btn.tag = index.rawValue
        btn.setTitle(title, for: .normal)
        btn.setBackgroundImage(UIImage(named: backImg + "_normal"), for: .normal)
        btn.setBackgroundImage(UIImage(named: backImg + "_selected"), for: .selected)
        //设置文字颜色
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor.darkGray, for: .selected)

        btn.addTarget(self, action: #selector(emoticonTypeBtnDidClick(btn:)), for: .touchUpInside)
        
        self.addArrangedSubview(btn)
        
        if index == .RECENT {
            btn.isSelected = true
            lastBtn = btn
        }
    }
    
    //btn 的点击事件
     @objc private func emoticonTypeBtnDidClick(btn : UIButton) {
        
        if btn.isSelected {
            return
        }
        
        lastBtn?.isSelected = false
        btn.isSelected = true
        lastBtn = btn
        
        //执行闭包对外抛出事件
        emoticonTypeSelectClosure?(EmoticonType.init(rawValue: btn.tag)!)
    }
    
    
    func setEmoticonTypeSelected(indexpath : IndexPath) {
        
        //根据tag值可以获取button
        let btn = self.viewWithTag(indexpath.section) as! UIButton
        
        if btn.isSelected {
            return
        }
        
        lastBtn?.isSelected = false
        btn.isSelected = true
        lastBtn = btn

        
    }
}









